import 'dart:async';

import 'package:connectivity/connectivity.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_base/componet/base_widget.dart';
import 'package:flutter_base/page/home_page.dart';
import 'package:flutter_base/util/utils.dart';
// import 'package:fluttertoast/fluttertoast.dart';

class LaunchPage extends StatefulWidget {
  @override
  LaunchPageState createState() => LaunchPageState();
}

class LaunchPageState extends State<LaunchPage> {
  StreamSubscription<ConnectivityResult>? subscription;
  bool network = true;
  Connectivity? connectivity;
  Timer? _timer;

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Center(
        child: DefaultText('这是启动页'),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    connectivity = Connectivity();

    ///第一帧渲染完成回调
    WidgetsBinding.instance?.addPostFrameCallback((callback) async {
      final result = await connectivity?.checkConnectivity();
      network = result == ConnectivityResult.wifi ||
          result == ConnectivityResult.mobile;
      getNetWorkChangeListen();
    });
  }

  void getNetWorkChangeListen() {
    ///监听网络变化
    subscription =
        connectivity?.onConnectivityChanged.listen((ConnectivityResult result) {
      network = result == ConnectivityResult.wifi ||
          result == ConnectivityResult.mobile;
      nextPage();
    });
    // if (isIOS) nextPage();
  }

  void nextPage() {
    if (network) {
      _timer = Timer(const Duration(seconds: 1), () {
        pushReplace(context, const MyHomePage(title: '基类封装'));
      });
    } else {
      ///无网络应该跳转到登录页面
      // Fluttertoast.showToast(msg: '无网络应该跳转到登录页面');
    }
  }
  @override
  void dispose() {
    super.dispose();
    subscription?.cancel();
  }
}
